/*! ******************************************************************************
 *
 * Created on 2022年3月4日
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.yzbdl.lanius.core.plugins.install;

import cn.hutool.core.collection.ConcurrentHashSet;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.plugins.KettleURLClassLoader;
import org.pentaho.di.core.plugins.Plugin;
import org.pentaho.di.core.vfs.KettleVFS;
import org.yzbdl.lanius.authorize.verification.jar.JarValidate;
import org.yzbdl.lanius.core.constant.LocalDir;
import org.yzbdl.lanius.core.event.EventContext;
import org.yzbdl.lanius.core.plugins.ClassLoaderManager;
import org.yzbdl.lanius.core.plugins.event.PluginAddEvent;
import org.yzbdl.lanius.core.plugins.metastore.LdrPluginEntity;
import org.yzbdl.lanius.util.LogUtil;

/**
 * 插件加载类
 *
 * @author hs@yzbdl.ac.cn
 */
public class PluginLoader {

    private static LogChannelInterface log = new LogChannel("PLUGIN_LOADER");

    /**
     * 未通过license校验的插件
     */
    private static ConcurrentHashSet<String> invalidSet = new ConcurrentHashSet<>(300);

    /**
     * 加载唯一的一个插件
     *
     * @param ldrPluginEntity
     */
    public static boolean loadOne(LdrPluginEntity ldrPluginEntity) {
        Plugin plugin = Plugin.from(ldrPluginEntity);
        KettleURLClassLoader classLoader;
        try {
            FileObject fileObject = KettleVFS.getFileObject(plugin.getPluginDirectory().toString());
            for (FileObject child : fileObject.getChildren()) {
                if (child.toString().endsWith(".jar")) {
                    if (!JarValidate.validate(child)) {
                        PluginLoader.log.logError("license认证失败: " + ldrPluginEntity.getPluginTypeName() + "/"
                                + ldrPluginEntity.getPluginId() + "/" + ldrPluginEntity.getVersion());
                        PluginLoader.invalidSet.add(ldrPluginEntity.getPluginTypeName() + "/" + ldrPluginEntity.getPluginId() + "/"
                                + ldrPluginEntity.getVersion());
                        throw new KettlePluginException("license认证失败: " + ldrPluginEntity.getPluginTypeName() + "/"
                                + ldrPluginEntity.getPluginId() + "/" + ldrPluginEntity.getVersion());
                    } else {
                        PluginLoader.invalidSet.remove(ldrPluginEntity.getPluginTypeName() + "/" + ldrPluginEntity.getPluginId() + "/"
                                + ldrPluginEntity.getVersion());
                    }
                }
            }
            classLoader = (KettleURLClassLoader) ClassLoaderManager.getInstance().getClassLoader(plugin);
            String mainClass = ldrPluginEntity.getMainClassName();
            Class<?> clazz = classLoader.loadClass(mainClass);
            if (clazz == null) {
                throw new KettlePluginException("无法加载类: " + mainClass);
            }

            ldrPluginEntity.getPluginTypeInstance().registryPlugin(ldrPluginEntity);
            EventContext.publish(new PluginAddEvent(ldrPluginEntity));
            return true;
        } catch (Exception e) {
            ClassLoaderManager.getInstance().removeClassLoader(plugin);
            String pluginPath = LocalDir.PLUGIN + LocalDir.separator + ldrPluginEntity.getPluginId() + LocalDir.separator
                    + ldrPluginEntity.getVersion();
            LogUtil.error("加载插件出错, 插件路径: " + pluginPath);
            return false;
        }
    }

    /**
     * 插件是否已授权
     *
     * @return
     */
    public static boolean isAuthorizedPlugin(String pluginTypeName, String pluginId, String version) {
        return !PluginLoader.invalidSet.contains(pluginTypeName + "/" + pluginId + "/" + version);
    }

}
